package com.bwt.sort;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;

public class BubbleSort {
    public static void main(String[] args) {
        int arr[] = {3, 9, -1, 10, -2};
        bubbleSort(arr);
        System.out.println("排序后的数组: "+Arrays.toString(arr));

        int arr2[] = new int[80000];
        for (int i = 0; i < 80000; i++) {
            arr2[i] = (int) (Math.random() * 8000000);
        }
        //System.out.println("排序前的数组2: "+ Arrays.toString(arr2));
        Date data = new Date();
        SimpleDateFormat simt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateS = simt.format(data);
        System.out.println("排序前的时间是:" + dateS);

        //测试冒泡排序
        bubbleSort(arr2);

        //System.out.println("排序后的数组2: "+Arrays.toString(arr));

        //排序后的时间:
        Date data2 = new Date();
        SimpleDateFormat simt2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateS2 = simt2.format(data2);
        System.out.println("排序后的时间是:" + dateS2);
        /*排序前的时间是:2022-07-10 00:12:31
        排序后的时间是:2022-07-10 00:12:53*/
    }

    private static void bubbleSort(int[] arr) {
        int temp = 0;
        boolean flag = false; //表示变量
        for (int j = 0; j < arr.length-1; j++) {
            for (int i = 0; i < arr.length - 1-j; i++) {
                if (arr[i] > arr[i + 1]) {
                    flag = true;
                    temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                }
            }
/*            System.out.println("第("+(j+1)+")趟排序后的数组");
            System.out.println(Arrays.toString(arr));*/
            if (!flag) {
                break;
            } else {
                flag = false; //重置flag , 进行下次判断
            }
        }
    }

}
